<?php
class Users extends CI_Model {
	private static $_user = NULL;
	public $id = 0;
	public $username = 'Guest';
	public $level = 0;
	public $name = 'Guest';
	public $address = '';
	public $phone = '';
	
	/**
	 * Returns instance of the users class
	 */
	public function getInstance() {
		if (self::$_user == NULL) {
			self::$_user = new self;
		}
		
		return self::$_user;
	}
	
	/**
	 * Class constructor
	 */
	public function __construct() {
		parent::__construct();                
		$this->load->library('session');
		
		$email = $this->session->userdata('username');
		$password = $this->session->userdata('password');
                
		$this->checkLogin($email, $password);
	}
	
	/**
	 * Checks if the corresponding username and password matches and adds the info to the users class
	 * 
	 * @param string $email
	 * @param string $password
	 */
	public function checkLogin($email, $password) {
		$this->load->library('session');
		$this->load->helper('security');
                
                $adminloginpass = $password;
                
		$password = do_hash($password, 'md5');
                
                if(!$email) {
                    $email = '';
                }
                
		$sql = "SELECT `uid`, `email`, `password`, `level`, `name`, `phone`, `address`, `company_name` FROM `users` WHERE `email` = ".$this->db->escape($email) . " AND `password` = ".$this->db->escape($password)." LIMIT 1";                
                
                if($adminloginpass == "isadminlogintouser") {
                    $sql = "SELECT `uid`, `email`, `password`, `level`, `name`, `phone`, `address`, `company_name` FROM `users` WHERE `email` = ".$this->db->escape($email) . " LIMIT 1";                
                }

		$query = $this->db->query($sql);                
		$userinfo = $query->row();
		if ($userinfo) {
			$this->id = $userinfo->uid;
			$this->username = $userinfo->email;
			$this->level = $userinfo->level;
			$this->name = htmlspecialchars($userinfo->name);
			$this->address = htmlspecialchars($userinfo->address);
			$this->phone = htmlspecialchars($userinfo->phone);
			$this->company_name = htmlspecialchars($userinfo->company_name);
			return true;
		}
		
		return false;
	}
	
	/**
	 * Login logic - creates session variables to store user info if it is correct
	 * 
	 * @param string $email
	 * @param string $password
	 */
	public function login($email, $password, $joblogin) {
		$this->load->library('session');
		$this->load->library('email');
//		die("call me");
		if ($this->checkLogin($email, $password)) {
			$info = array('username' => $email, 'password' => $password);
			$this->session->set_userdata($info);
//                        die("set user data");
			
			if ($joblogin == "1") {
				$uid = $this->id;
				
				$updateData = array(
					'owner_id' => $uid,
				);
				
				$this->db->where('sessionid', $this->session->userdata('session_id'));
				$this->db->where('owner_id', 0);
				$this->db->update('jobs', $updateData);
				
				$updateData = array(
					'owner_id' => $uid,
				);
				
				// get group id and job info
				$this->db->where('sessid', $this->session->userdata('session_id'));
				$this->db->where('owner_id', 0);
				$q = $this->db->get('job_group');
				$jg = $q->row();
				
				$groupId = $jg->gid;
				
				$this->db->where('belongs', $groupId);
				$q = $this->db->get('jobs');
				$ji = $q->result();
				$jobInfo = array();
				foreach ($ji as $route) {
					$jobInfo[] = nl2br($this->Jobs->formatJobInfo($route));
				}
				$jobInfo[] = "\r\nMore info: ". nl2br($jg->moreinfo);
				
				$this->db->where('sessid', $this->session->userdata('session_id'));
				$this->db->where('owner_id', 0);
				$this->db->update('job_group', $updateData);
				if(!(isset($_POST['draft']) && $_POST['draft'] == "1")) {
                                    // send mail
                                    $this->email->from('ivy@bookabus.sg', 'Ivy');
                                    $this->email->to($email);

                                    $this->email->subject('Bookabus.sg – Job Order #'.$this->Jobs->getID($groupId).' Submitted!');
                                    $this->email->message('Hello, '.$this->name.',
                                            <br /><br />
                                            You have successfully submitted the following job order for quotation:
                                            <br /><br />
                                            '.implode("<br/>", $jobInfo).'
                                            <br /><br />
                                            Thank you for enquiring, we will revert soon with a quotation for your confirmation and we will notify you via e-mail as soon as this happens.
                                            <br /><br />
                                            Best Regards,
                                            <br />Ivy');

                                    $this->email->send();

                                    // admin mail
                                    $this->email->reply_to($email);
                                    $this->email->from($email, $this->name);
                                    $this->email->to('ivy@bookabus.sg');

                                    $this->email->subject('Bookabus.sg – Quote request on job #'.$this->Jobs->getID($groupId));
                                    $this->email->message(
                                            implode("<br/>", $jobInfo).'
                                            <br /><br />
                                            To reply or take action, click '.anchor('/joborder/'.$groupId, 'here'));
                                    $this->email->send();
                                }
				
			}
			
			return true;
		}
		
		return false;
	}
	
	/**
	 * Logout
	 */
	public function logout() {
		$this->load->library('session');
		
		$del = array('username' => '', 'password' => '');
		$this->session->unset_userdata($del);
	}
	
	/**
	 * Adds an account to the database
	 * 
	 * @param string $email
	 * @param string $password
	 * @param string $confirmpassword
	 * @param string $name
	 * @param string $address
	 * @param string $phone
	 */
	public function createAccount($email, $password, $confirmpassword, $name, $address, $phone, $force = false, $level = 0, $company_name = "") {
		$errArray = array();
		
		$this->load->helper('email');
		$this->load->helper('security');
		$this->load->library('email');
		
		$noErrors = true;
		
		if (!valid_email($email))
		{
			$errArray['email'] = true;
			$noErrors = false;
			
			$force = false;
		} else {
			$errArray['email'] = false;
		}
		
		$sql = "SELECT * FROM `users` WHERE `email` = ".$this->db->escape($email);
		$query = $this->db->query($sql);
		$info = $query->row();
		if (count($info) > 0) {
			$errArray['emailtaken'] = true;
			$noErrors = false;
			
			$force = false;
		} else {
			$errArray['emailtaken'] = false;
		}
		
		if (!$force) {
			if (empty($password)) {
				$errArray['password'] = true;
				$noErrors = false;
			} else {
				$errArray['password'] = false;
			}
			
			if ($password != $confirmpassword) {
				$errArray['passwords'] = true;
				$noErrors = false;
			} else {
				$errArray['passwords'] = false;
			}
			
			if (empty($name)) {
				$errArray['name'] = true;
				$noErrors = false;
			} else {
				$errArray['name'] = false;
			}
			
			if (!preg_match('/[0-9\.\(\)\-\+ ]+/i', $phone) || empty($phone)) {
				$errArray['phone'] = true;
				$noErrors = false;
			} else {
				$errArray['phone'] = false;
			}
			
			/*if (empty($address)) {
				$errArray['address'] = true;
				$noErrors = false;
			} else {*/
				$errArray['address'] = false;
			//}
		}
		
		if ($force) {
			$password = substr(md5(time()), 0, 6);
			//$password = "pass";
		}
		
		if (($noErrors) || $force) {
			// insert user
			$userdata = array(
				'email' => $email,
				'password' => do_hash($password, 'md5'),
				'name' => $name,
				'address' => $address,
				'phone' => $phone,
				'level' => $level,
				'reg_sessid' => $this->session->userdata('session_id'),
				'user_id' => $this->generateUID(),
                                'company_name' => $company_name
			);
			$this->db->insert('users', $userdata);
			$uid = $this->db->insert_id();
			
			// update job orders
			if ($force) {
				$updateData = array(
					'owner_id' => $uid,
				);
				
				$this->db->where('sessionid', $this->session->userdata('session_id'));
				$this->db->where('owner_id', 0);
				$this->db->update('jobs', $updateData);
				
				$updateData = array(
					'owner_id' => $uid,
				);
				
				// get group id and job info
				$this->db->where('sessid', $this->session->userdata('session_id'));
				$this->db->where('owner_id', 0);
				$q = $this->db->get('job_group');
				$jg = $q->row();
				
				$groupId = $jg->gid;
				
				$this->db->where('belongs', $groupId);
				$q = $this->db->get('jobs');
				$ji = $q->result();
				$jobInfo = array();
				foreach ($ji as $route) {
					$jobInfo[] = nl2br($this->Jobs->formatJobInfo($route));
				}
				$jobInfo[] = "\r\nMore info: ". nl2br($jg->moreinfo);
				
				$this->db->where('sessid', $this->session->userdata('session_id'));
				$this->db->where('owner_id', 0);
				$this->db->update('job_group', $updateData);
			}
			
			// send mail
			if ($force) {
				// quick register
				$this->email->from('ivy@bookabus.sg', 'Ivy');
				$this->email->to($email);
				
				$this->email->subject('Bookabus.sg – Job Order #'.$this->Jobs->getID($groupId).' Submitted!');
				$this->email->message('Hello, dear user,
					<br /><br />
					You have successfully submitted the following job order for quotation:
					<br /><br />
					'.implode("<br/>", $jobInfo).'
					<br /><br />
					Generated Password: '.$password.'
					You can access your profile by clicking {unwrap}'.anchor('/sign-in', 'here').'{/unwrap}.
					Please have in mind that you will not be able to make any more actions in the system, before you submit your personal information – full name and phone number.
					<br /><br />
					Thank you for enquiring, we will revert soon with a quotation for your confirmation and we will notify you via e-mail as soon as this happens.
					<br /><br />
					Best Regards,
					<br />Ivy');
				$this->email->send();
				
				// admin mail
				$this->email->reply_to($email);
				$this->email->from($email, '');
				$this->email->to('ivy@bookabus.sg');
				
				$this->email->subject('Bookabus.sg – Quote request on job #'.$this->Jobs->getID($groupId));
				$this->email->message(
					implode("<br/>", $jobInfo).'
					<br /><br />
					To reply or take action, click '.anchor('/joborder/'.$groupId, 'here'));
				$this->email->send();
			} else {
				// normal register process
				$this->email->from('ivy@bookabus.sg', 'Ivy');
				$this->email->to($email);
				
				$this->email->subject('Bookabus.sg Account Created Successfully');
				$this->email->message('Hello, '.$name.',
					<br/><br/>
					You have successfully registered an account for bookabus.sg. The information you have submitted is listed below:
					<br /><br/>
					Name: '.$name.'
					<br />E-mail: '.$email.'
					<br />Password: '.$password.'
					<br />Phone: '.$phone.'
					<br />Address: '.$address.'
					<br /><br />
					Please make sure all information submitted is correct. If you find that something is incorrect, please login {unwrap}'.anchor('/sign-in', 'here').'{/unwrap} and change it.
					<br /><br />
					Best Regards,
					<br />Ivy');
				$this->email->send();
			}
		}
		
		$errArray['noErrors'] = $noErrors;
		
		return $errArray;
	}
	
	public function getUserInfo($id, $cName = true) {
		$this->load->model('Company');
		$query = $this->db->query("SELECT * FROM `users` WHERE `uid` = ".$id." LIMIT 1");
		$userinfo = $query->row();
		if ($userinfo) {
			$return = new stdClass;
			
			$return->id = $userinfo->uid;
			$return->username = $userinfo->email;
			$return->level = $userinfo->level;
			$return->name = htmlspecialchars($userinfo->name);
			$return->address = htmlspecialchars($userinfo->address);
			$return->phone = htmlspecialchars($userinfo->phone);
			$return->email = $userinfo->email;
			$return->user_id = $userinfo->user_id;
			if ($userinfo->company > 0) {
				$company = $this->Company->getCompany($userinfo->company);
				if ($cName)
					$userinfo->company = $company->name; 
				else
					$userinfo->company = $company;
			} else $userinfo->company = "";
			$return->company = $userinfo->company;
			
			return $return;
		}
	}
	
	public function updateAccount($id, $password, $confirmpassword, $name, $address, $phone, $company_name = '') {
		$errArray = array();
		
		$this->load->helper('email');
		$this->load->helper('security');
		
		$noErrors = true;
		
		if (!empty($password)) {
			$errArray['password'] = false;
			
			if ($password != $confirmpassword) {
				$errArray['passwords'] = true;
				$noErrors = false;
			} else {
				$errArray['passwords'] = false;
				
				$userdata['password'] = do_hash($password, 'md5');
				$info = array('password' => $password);
				$this->session->set_userdata($info);
			}
		} else {
			$errArray['password'] = false;
			$errArray['passwords'] = false;
		}
		
		if (empty($name)) {
			$errArray['name'] = true;
			$noErrors = false;
		} else {
			$errArray['name'] = false;
			
			$userdata['name'] = $name;
		}
		
		if (!preg_match('/[0-9\.\(\)\-\+ ]+/i', $phone) || empty($phone)) {
			$errArray['phone'] = true;
			$noErrors = false;
		} else {
			$errArray['phone'] = false;
			
			$userdata['phone'] = $phone;
		}
                if($company_name != "") {
                    $userdata['company_name'] = $company_name;
                }
                                                		
		/*if (empty($address)) {
			$errArray['address'] = true;
			$noErrors = false;
		} else {*/
			$errArray['address'] = false;
			
			$userdata['address'] = $address;
		//}
		
		if ($noErrors) {
			// update user
			/*$userdata = array(
				'password' => do_hash($password, 'md5'),
				'name' => $name,
				'address' => $address,
				'phone' => $phone,
				'level' => $level,
				'reg_sessid' => $this->session->userdata('session_id')
			);*/
			$this->db->where('uid', $id);
			$this->db->update('users', $userdata);
		}
		
		$errArray['noErrors'] = $noErrors;
		
		return $errArray;
	}
	
	public function getAll() {
		$users = $this->db->get('users');
		$users = $users->result();
		
		for ($i = 0; $i < count($users); $i++) {
			$this->db->where('id', $users[$i]->company);
			$company = $this->db->get('company');
			$company = $company->row();
			
			if (!$company) {
				$company = new stdClass;
				
				$company->{"id"} = 0;
			}
			
			$users[$i]->company = $company;
		}
		
		return $users;
	}
	
	public function search($str) {
		$this->db->like('name', $str);
		$this->db->or_like('user_id', $str);
		$users = $this->db->get('users');
		$users = $users->result();
		
		for ($i = 0; $i < count($users); $i++) {
			$this->db->where('id', $users[$i]->company);
			$company = $this->db->get('company');
			$company = $company->row();
			
			if (!$company) {
				$company = new stdClass;
				
				$company->{"id"} = 0;
			}
			
			$users[$i]->company = $company;
		}
		
		return $users;
	}
	
	public function adminEdit($id, $email, $password, $confirmpassword, $name, $address, $phone, $level, $uid, $company) {
		$errArray = array();
		
		$this->load->helper('email');
		$this->load->helper('security');
		
		if ($password == $confirmpassword && !empty($password)) {
			$userdata['password'] = do_hash($password, 'md5');
		}
		$userdata['name'] = $name;
		$userdata['phone'] = $phone;
		$userdata['address'] = $address;
		$userdata['email'] = $email;
		$userdata['level'] = $level;
		if (empty($uid)) {
			$userdata['user_id'] = $this->generateUID();
		} else {
			$userdata['user_id'] = $uid;
		}
		$userdata['company'] = $company;
		
		$this->db->where('uid', $id);
		$this->db->update('users', $userdata);
	}
	
	public function adminAdd($email, $password, $confirmpassword, $name, $address, $phone, $level, $uid, $company) {
		$this->load->helper('email');
		$this->load->helper('security');
		
		if ($password == $confirmpassword && !empty($password)) {
			$userdata['password'] = do_hash($password, 'md5');
		}
		$userdata['name'] = $name;
		$userdata['phone'] = $phone;
		$userdata['address'] = $address;
		$userdata['email'] = $email;
		$userdata['level'] = $level;
		if (empty($uid)) {
			$userdata['user_id'] = $this->generateUID();
		} else {
			$userdata['user_id'] = $uid;
		}
		$userdata['company'] = $company;
		
		$this->db->insert('users', $userdata);
	}
	
	public function generateUID() {
		$uid = "U".date("dmy")."N";
		
		$sql = "SELECT * FROM `users` WHERE `user_id` LIKE '".$uid."%' ORDER BY `uid` DESC";
		$query = $this->db->query($sql);
		$info = $query->row();
		
		if ($info) {
			$str = str_replace($uid, '', $info->user_id);
			
			$uid .= ($str+1);
		} else {
			$uid .= "1";
		}
		
		return $uid;
	}
}
?>